import { Injectable } from '@angular/core';
import {StorageProvider} from "@providers/storage";
import {ActionSheetController, ModalController} from "ionic-angular";
import {HttpProvider} from "@providers/http";

/*
  Generated class for the AddressProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class AddressProvider {

  userInfo: any = this.storage.read("userInfo") || {};
  public url: string = "/JLInterface/getDQXX.do"; //访问地址
  constructor(
    private storage: StorageProvider,
    private actionSheetCtrl: ActionSheetController,
    private modalCtrl: ModalController,
    private http: HttpProvider,) { }

  Address = [];
  //选择地址调用
  //LEVELS 最大的级别 省 1市 2 区 3 (可控制任意省市区一级结束),PARENT地区的代码(可控制省市区任意一级开始开始)
  //okFun 选择完成后的回调函数
  selectAddress(okFun: (Address: any[]) => void, LEVELS?, PARENT?) {
    this.Address = [];
    this.getAddress(okFun, LEVELS, PARENT);
  }

  //内部自己调用的方法
  private getAddress(okFun: (Address: any[]) => void, LEVELS?, PARENT?) {
    //获取地址数据
    var json = { "PID": "", "SK01": "", "dataType": "Json", "QryType": "Bill" };
    if (PARENT) json["PARENT"] = PARENT;
    if (!LEVELS) LEVELS = 3;
    this.http.post(this.url, {
      data: JSON.stringify(json),
      XmlData: JSON.stringify(json),
      SessionID: this.userInfo.SessionID,
      rmstoken:'127.0.0.1'
    }).subscribe(message => {
      if (!message.data && message.list) {
        message = { data: { returnList: message.list } }
      }
      if (message.data.returnList.length > 0) {
        let temp = [];
        let obj: any[] = message.data.returnList;
        if (LEVELS < obj[0].LEVELS) return;
        let titleText = "请选择地址";
        if (obj[0].LEVELS == 1) {
          titleText = "请选择省";
        } else if (obj[0].LEVELS == 2) {
          titleText = "请选择市";
        } else if (obj[0].LEVELS == 3) {
          titleText = "请选择区";
        }
        for (var i = 0; i < obj.length; i++) {
          let item: any = obj[i];
          temp.push({
            text: obj[i].VALUE,
            handler: () => {
              this.Address.push(item);
              if (LEVELS == item.LEVELS) {
                okFun(this.Address);
              } else {
                this.getAddress(okFun, LEVELS, item.KEY);
              }
            }
          });
        }
        let actionSheet = this.actionSheetCtrl.create({
          title: titleText,
          buttons: temp
        });
        actionSheet.present();
      }
    }, error => {
    });
  }

  addressSelector(addressList?): Promise<any> {
    return new Promise((resolve) => {
      let _modal = this.modalCtrl.create("AddressSelectorPage", {addressList: addressList});
      _modal.onDidDismiss((v) => {
        if (v) resolve(v)
      });
      _modal.present();
    })
  }

}
